//
//  TorchConfig.m
//  Flashlight
//
//  Created by Eric on 4/14/13.
//  Copyright (c) 2013 Saick. All rights reserved.
//

#import "TorchConfig.h"
#import "global_Header.h"

@implementation TorchConfig

static TorchConfig* sharedConfig;

- (void)dealloc
{
    [self writeCurrentToUserDefault];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [super dealloc];
}

+ (TorchConfig *)sharedConfig
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedConfig = [[self alloc] init];
    });
    
    return sharedConfig;
}

- (id)init
{
    if (self = [super init]) {
        [self restoreFromUserDefault];
        
        if (![[NSUserDefaults standardUserDefaults] boolForKey:kFirstInstall]) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kFirstInstall];
            _fStopTorch         = 0.2f;
            _isSavingAutomatic  = YES;
            _isDefaultOn        = YES;
            _isDisableAutoLock  = YES;
            _isEnableFullScreenControl = NO;
            
            [self writeCurrentToUserDefault];
        }
        
        NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
        [notifCenter addObserver:self
                        selector:@selector(applicationDidEnterBackground:)
                            name:UIApplicationDidEnterBackgroundNotification
                          object:nil];
        [notifCenter addObserver:self
                        selector:@selector(applicationDidBecomeActive:)
                            name:UIApplicationDidBecomeActiveNotification
                          object:nil];
    }
    return self;
}

- (void)restoreFromUserDefault
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    _fStopTorch         = [[userDefault objectForKey:STOP_USING_TORCH] floatValue];
    _isSavingAutomatic  = [userDefault boolForKey:SAVING_AUTOMATIC];
    _isDefaultOn        = [userDefault boolForKey:DEFAULT_TURN_ON];
    _isDisableAutoLock  = [userDefault boolForKey:DISABLE_AUTO_LOCK];
    _isEnableFullScreenControl = [userDefault boolForKey:FULLSCREENCONTROL];
    
    [self updateSettingAffect];
}

- (void)writeCurrentToUserDefault
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:[NSString stringWithFormat:@"%.2f", _fStopTorch] forKey:STOP_USING_TORCH];
    [userDefault setBool:_isSavingAutomatic forKey:SAVING_AUTOMATIC];
    [userDefault setBool:_isDefaultOn forKey:DEFAULT_TURN_ON];
    [userDefault setBool:_isDisableAutoLock forKey:DISABLE_AUTO_LOCK];
    [userDefault setBool:_isEnableFullScreenControl forKey:FULLSCREENCONTROL];
    
    [userDefault synchronize];
}

- (void)updateSettingAffect
{
    if (_isDisableAutoLock) {
        [UIApplication sharedApplication].idleTimerDisabled = YES;
    } else {
        [UIApplication sharedApplication].idleTimerDisabled = NO;
    }
}

#pragma mark - application notif

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    // 程序首次安装启动时，未能读取设置束中的内容，故需要写入一个特别的字段，到UserDefault中，读取到了说明就不是第一次启动，需要实时写入UserDefault，否则不写（默认数值会变无效）。
    // 首次启动后，程序不退出，进入后台，修改设置束，再返回，即可获取到数据
    
    [self writeCurrentToUserDefault];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [self restoreFromUserDefault];
}

@end
